/*
 * HttpUtil.java
 *
 * Copyright (C) 2005-2008 Tommi Laukkanen
 * http://www.substanceofcode.com
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.substanceofcode.utils;

import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;

/**
 *
 * @author Tommi Laukkanen
 */
public class HttpUtil extends HttpAbstractUtil {

    /** Total bytes transfered */
    private static long totalBytes = 0;
	private static String userAgent = "curl/7.18.0 (i486-pc-linux-gnu) libcurl/7.18.0 OpenSSL/0.9.8g zlib/1.2.3.3 libidn/1.1";
    
    /** Creates a new instance of HttpUtil */
    public HttpUtil() {
    }

	public static void setUserAgent(String userAgent) {
		HttpUtil.userAgent = userAgent;
	}

    public static String doPost(String url, String query) throws IOException, Exception {
        return doRequest(url, query, HttpConnection.POST);
    }

    public static String doGet(String url, String query) throws IOException, Exception {
        return doRequest(url+"?"+query, "", HttpConnection.GET);
    }

    public static String doRequest(String url, String query, String requestMethod) throws IOException, Exception {
		String response = "";
        int status = -1;
		boolean redirected = false;
        String auth = null;
        InputStream is = null;
        OutputStream os = null;
        HttpConnection con = null;

        while (con == null) {
            con = (HttpConnection)Connector.open(url);
            con.setRequestMethod(requestMethod);
            if (username != null && password != null && username.length() > 0) {
                String userPass;
                Base64 b64 = new Base64();
                userPass = username + ":" + password;
                userPass = b64.encode(userPass.getBytes());
                con.setRequestProperty("Authorization", "Basic " + userPass);
            }
            con.setRequestProperty("User-Agent", userAgent);
            con.setRequestProperty("Connection", "close");
            con.setRequestProperty("Host", con.getHost()+":"+con.getPort());
            con.setRequestProperty("Accept", "*/*");
			if (query.length() > 0) {
	            con.setRequestProperty("Content-Length", "" + query.length());
			}
            con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            os = con.openOutputStream();
            Log.add("Posting to URL: "+url+":"+query);
            if(query.length() > 0) {
                os.write(query.getBytes());
            }
            os.close();
            os = null;

            status = con.getResponseCode();
            Log.add("response code"+status);
            switch (status) {
				case HttpConnection.HTTP_OK:
					break;
				case HttpConnection.HTTP_TEMP_REDIRECT:
				case HttpConnection.HTTP_MOVED_TEMP:
				case HttpConnection.HTTP_MOVED_PERM:
					redirected = true;
					url = con.getHeaderField("location");
					con.close();
					con = null;
					break;
				case 100:
					throw new IOException("unexpected 100 Continue");
				default:
					con.close();
					con = null;
					throw new IOException("Response status not OK:" + status);
            }
        }

        is = con.openInputStream();
		if (!redirected) {
			response = getUpdates(con, is, os);
		} else {
            try {
                if (con != null) {
                    con.close();
                }
                if (os != null) {
                    os.close();
                }
                if (is != null) {
                    is.close();
                }
            } catch (IOException ioe) {
                throw ioe;
            }
		}

		return response;
	}

    private static String getUpdates(HttpConnection con, InputStream is, OutputStream os)  throws IOException {
        StringBuffer stb = new StringBuffer();
        int ch = 0;
        try {
            int n = (int)con.getLength();
            if(n != -1) {
                for(int i = 0; i < n; i++) {
                    if((ch = is.read()) != -1) {
                        stb.append((char) ch);
                    }
                }
            } else {
                while((ch = is.read()) != -1) {
                    n = is.available();
                    stb.append((char) ch);
                }
            }
        } catch (IOException ioe) {
            throw ioe;
        } finally {
            try {
                if (con != null) {
                    con.close();
                }
                if (os != null) {
                    os.close();
                }
                if (is != null) {
                    is.close();
                }
            } catch (IOException ioe) {
                throw ioe;
            }
        }
        return stb.toString();
    }
}
